import sys


def input_course_info():
    course_dict = {}
    while True:
        try:
            week_day = input("请输入周几（1-7表示周一到周日）: ")
            if not week_day.isdigit() or not (1 <= int(week_day) <= 7):
                print("输入错误，请输入1-7之间的数字表示周一到周日。")
                continue
            week_day = int(week_day)

            course_name = input("请输入课程名称: ")
            course_time = input("请输入上课时间（按整点计算，例如8表示8点）: ")
            if not course_time.isdigit() or not (0 <= int(course_time) < 24):
                print("输入错误，请输入0-23之间的数字表示时间。")
                continue
            course_time = int(course_time)

            if week_day not in course_dict:
                course_dict[week_day] = {}

            if course_time in course_dict[week_day]:
                print("时间冲突，请重新输入。")
                continue

            course_dict[week_day][course_time] = course_name

            while True:
                choice = input("是否继续输入另一节课信息？（yes/no）: ").strip().lower()
                if choice == 'yes':
                    break
                elif choice == 'no':
                    return course_dict
                else:
                    print("无效输入，请输入yes或no。")

        except Exception as e:
            print(f"输入错误: {e}")

    # 用户选择是否继续输入
    while True:
        choice = input("是否继续输入另一节课信息？（yes/no）: ").strip().lower()
        if choice == 'yes':
            temp_dict = input_course_info()
            for day, times in temp_dict.items():
                if day not in course_dict:
                    course_dict[day] = {}
                for time, course in times.items():
                    if time in course_dict[day]:
                        print(f"时间冲突：{day}天{time}点已有{course_dict[day][time]}课")
                        sys.exit()
                    course_dict[day][time] = course
        elif choice == 'no':
            break
        else:
            print("无效输入，请输入yes或no。")

    return course_dict


def merge_course_info(existing_dict, new_dict):
    for week_day, times in new_dict.items():
        for time, course in times.items():
            if week_day in existing_dict and time in existing_dict[week_day]:
                print(f"时间冲突：第{week_day}周{time}点已有{existing_dict[week_day][time]}课")
                print(f"冲突课程信息：第{week_day}周{time}点 {existing_dict[week_day][time]}")
                sys.exit()
        if week_day not in existing_dict:
            existing_dict[week_day] = {}
        existing_dict[week_day].update(times)
    return existing_dict


def read_course_file(file_name):
    try:
        with open(file_name, 'r') as file:
            content = file.read()
            course_dict = eval(content)
            return course_dict
    except FileNotFoundError:
        return {}
    except Exception as e:
        print(f"读取文件错误: {e}")
        return {}


def write_course_file(file_name, course_dict):
    with open(file_name, 'w') as file:
        file.write(str(course_dict))


def main():
    file_name = 'course_schedule.txt'

    # 读取已有课程信息
    existing_dict = read_course_file(file_name)

    # 输入新的课程信息
    new_dict = input_course_info()

    # 合并课程信息
    merged_dict = merge_course_info(existing_dict, new_dict)

    # 写入文件
    write_course_file(file_name, merged_dict)

    # 格式化并打印
    for week_day, times in merged_dict.items():
        week_day_name = ["星期1", "星期2", "星期3", "星期4", "星期5", "星期6", "星期7"][week_day - 1]
        course_in_week = "\t".join(f"{time}点有{name}课" for time, name in sorted(times.items()))
        print(f"{week_day_name}：{course_in_week}")


if __name__ == "__main__":
    main()